/**
 * 公共请求方法
 */
import request from 'reqwest';

var methods = {
    get(url, data, method) {
        return new Promise((resolve, reject) => {
            request({
                url: url,
                method: 'GET',
                data: data,
                credentials: 'include',
                crossOrigin:true
            }).then((data) => {
                return data;
            })
                .then(json => {
                    resolve(json);
                })
                .catch(err => {
                    reject(err);
                });
        });
    },
    post(url, data, msg) {
        let json = data || {};
        return new Promise((resolve, reject) => {
            request({
                url: url,
                contentType: "application/json",
                method: 'POST',
                credentials: 'include',
                crossOrigin:true,
                data: JSON.stringify(json)
            }).then((data) => {
                if (data.code === 0) {
                    return data.data;
                } else {
                    return msg || data.msg
                }
            })
                .then(json => {
                    resolve(json);
                })
                .catch(err => {
                    reject(err);
                });
        });
    },
    addPost(url, data, msg) {
        let json = data || {};
        return new Promise((resolve, reject) => {
            request({
                url: url,
                contentType: "application/json",
                method: 'POST',
                credentials: 'include',
                crossOrigin:true,
                data: JSON.stringify(json)
            }).then((data) => {
                return data;
            })
                .then(json => {
                    resolve(json);
                })
                .catch(err => {
                    reject(err);
                });
        });
    },
    postForm(url, form, msg) {
        return new Promise((resolve, reject) => {
            request({
                url: url,
                method: 'POST',
                data: form,
                dataType:'json',
                cache:false,
                contentType: false,
                processData: false,
            }).then((data) => {
                return data;
            })
                .then(json => {
                    resolve(json);
                })
                .catch(err => {
                    reject(err);
                });
        });
    },
}

export default methods;
